package com.gdufe.firesafe.controller;

import com.gdufe.firesafe.model.entity.MessageEntity;
import com.gdufe.firesafe.model.entity.UserEntity;
import com.gdufe.firesafe.service.MessageService;
import com.gdufe.firesafe.utils.MessageEmitterManager;
import com.gdufe.firesafe.utils.R;
import com.gdufe.firesafe.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.List;


/**
 * 消息
 */
@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private MessageService messageService;

    /**
     * 发送测试消息
     */
    @GetMapping("/test/data")
    public R test() {
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setContent("test");
        try {
            SseEmitter emitter = MessageEmitterManager.get(TokenUtils.getCurrentUser().getId());
            emitter.send(messageEntity);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.ok();
    }

    /**
     * 获取未读消息个数
     */
    @GetMapping("/getUnreadCount")
    public R getUnreadCount() {
        Integer unreadCount = messageService.getUnreadCount();
        return R.ok().putData(unreadCount);
    }

    /**
     * 获取不同类型的消息列表
     */
    @GetMapping("/list/{type}")
    public R list(@PathVariable("type") Integer type) {
        List<MessageEntity> list = messageService.list(type);
        return R.ok().putData(list);
    }

    /**
     * 客户端获取SSE的Emitter，以接收流式信息
     */
    @GetMapping("/getEmitter")
    public SseEmitter getEmitter() {
        UserEntity currentUser;
        try {
            currentUser = TokenUtils.getCurrentUser();
        } catch (NullPointerException e) {
            return null;
        }
        Integer userId = currentUser.getId();
        return MessageEmitterManager.newEmitter(userId);
    }

    /**
     * 消息设为已读
     */
    @PutMapping("/read/{messageId}")
    public R readMessage(@PathVariable("messageId") Integer messageId) {
        if(messageService.read(messageId)) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * 全部已读
     */
    @PutMapping("/readAll")
    public R readAll() {
        if(messageService.readAll()) {
            return R.ok();
        } else {
            return R.error();
        }
    }

}
